package com.cos.controller;

import com.cos.constant.LoginSuccess;
import com.cos.constant.Redis;
import com.cos.fegin.api.ItemService;
import com.cos.vo.Customer;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.enums.scope.AuthBaiduScope;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthBaiduRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;

@Controller
@RequestMapping("/oauth")
public class JustAutoController {
    @Autowired
    private ItemService itemService;
    @RequestMapping("/login")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        //这里是跳转第三方授权页面
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public Object login(AuthCallback callback, HttpSession session) {
       // System.out.println("callback:code:" + callback.getCode() + ",state:" + callback.getState());
        AuthRequest authRequest = getAuthRequest();
        AuthResponse authResp = authRequest.login(callback);

        if (authResp.ok()) {
            AuthUser data = (AuthUser) authResp.getData();
            String username = data.getUsername();
            Customer customer = itemService.checkUsername(data.getUsername());
            if (customer==null) {
                //保证对象是不变的
                customer=new Customer();
                customer.setUsername(username);
                customer.setOauthId(data.getUuid());
                itemService.addUser(customer);
            }
            //将用户信息保存到redis中
            session.setAttribute(LoginSuccess.LOGIN_SUCCESS,customer);
            return "redirect:http://localhost/home/";
        }else{
            return "redirect:http://localhost/auth/login.html";
        }
    }

    private AuthRequest getAuthRequest() {
        return new AuthBaiduRequest(AuthConfig.builder()
                .clientId("baGUfVVOcwfyQ65aidkje0Db")
                .clientSecret("LcwBEUGADWgFIbE6axRAAk81ALIPI4og")
                .redirectUri("http://localhost/auth/oauth/callback")//授权以后跳转的接口
                .build());
    }
}
